<template>
  <div class="flex flex-row">
    <div class="w-80">
      <ARow class="flex gap-3 w-80" ref="elNums">
        <ACol
            class="drag-item mb-3"
            v-for="num in nums"
            :key="num"
            :data-id="num"
        >
          <div class="w-24 h-24 border border-gray-300 bg-white text-lg flex items-center justify-center cursor-pointer">{{ num }}</div>
        </ACol>
      </ARow>

      <div class="desc">
        <span>注意：</span>
        <span><b>data-id</b> 中配置的属性, 通过sortable.toArray()可获取序列化后的顺序。</span>

        <p>排序后的顺序为：{{ sortArr }}</p>
      </div>
    </div>

    <div class="flex flex-row gap-4 ml-40">
      <AList class="w-72 bg-white h-96 overflow-y-auto overflow-x-hidden" bordered :data-source="numsLeft" ref="elLeft">
        <template #renderItem="{ item }">
          <AListItem class="cursor-pointer">{{ item }}</AListItem>
        </template>
      </AList>

      <AList class="w-72 bg-white h-96 overflow-y-auto overflow-x-hidden" bordered :data-source="numsRight" ref="elRight">
        <template #renderItem="{ item }">
          <AListItem class="cursor-pointer">{{ item }}</AListItem>
        </template>
      </AList>
    </div>
  </div>

</template>

<script lang="ts" setup>
import Sortablejs from 'sortablejs'
import type Sortable from 'sortablejs'


const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const elNums = ref( null )

const numsLeft = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const numsRight = [11, 12, 13, 14, 15, 16, 17, 18, 19]
const elLeft = ref(null)
const elRight = ref(null)

let sortable: Sortable

const sortArr = ref(nums)

onMounted(() => {
  sortable = Sortablejs.create(
      unref(elNums).$el,
      {
        animation: 300,
        delay: 400,
        delayOnTouchOnly: true,
        handle: '.drag-item ',
        dataIdAttr: 'data-id',
        onEnd() {
          sortArr.value = sortable.toArray().map( it => Number(it) )
        }
      }
  )

  new Sortablejs(unref(elLeft).$el.querySelector('.ant-list-items'), {
    group: 'shared', // set both lists to same group
    animation: 150
  })

  new Sortablejs(unref(elRight).$el.querySelector('.ant-list-items'), {
    group: 'shared', // set both lists to same group
    animation: 150
  })
})
</script>